package com.cheung.leetcode.arr;

import java.util.Arrays;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.arr
 * @Author :  cheungming
 * @CreateTime : 2024-04-29 11:21:09
 * @Description : LCR146题
 * @Version : 1.0
 */
public class CodeLcr146 {

    public static int[] spiralArray(int[][] array) {
        if (array.length == 0) {
            return new int[]{};
        }

        int top = 0;
        int bottom = array.length - 1;

        int left = 0;
        int right = array[0].length - 1;

        int n = array.length * array[0].length;

        int[] result = new int[n];
        int count = 0;
        while (count < n) {
            // 从左到右，行不变
            for (int i = left; i <= right; i++) {
                result[count++] = array[top][i];
            }
            if (++top > bottom) {
                break;
            }

            // 从上到下,列不变
            for (int i = top; i <= bottom; i++) {
                result[count++] = array[i][right];
            }
            if (--right < left) {
                break;
            }


            // 从右到左，行不变
            for (int i = right; i >= left; i--) {
                result[count++] = array[bottom][i];
            }
            if (--bottom < top) {
                break;
            }

            // 从下到上，列不变
            for (int i = bottom; i >= top; i--) {
                result[count++] = array[i][left];
            }
            if (++left > right) {
                break;
            }

        }

        return result;
    }

    public static void main(String[] args) {
        int[][] array = {{1, 2, 3, 4}, {12, 13, 14, 5}, {11, 16, 15, 6}, {10, 9, 8, 7}};
        System.out.println(Arrays.toString(spiralArray(array)));

        System.out.println(Arrays.toString(spiralArray(new int[][]{})));

        System.out.println(Arrays.toString(spiralArray(new int[][]{{2, 3}})));

        System.out.println(Arrays.toString(spiralArray(new int[][]{{2}, {3}, {4}})));
    }
}
